<!-- 主页的图片数据管理 -->
<template>
  <div>
    <Layout>
      <template #search>
        <el-form
          :model="queryParams"
          ref="queryRef"
          v-show="showSearch"
          label-width="68px"
          inline
        >
          <el-form-item label="素材分类" prop="materialType">
            <InputSelect
              text="请输入素材分类"
              :modelValue="queryParams.materialType"
              :options="classifyList"
              @update:modelValue="handleMaterialTypeSearch"
            />
          </el-form-item>
          <el-form-item label="展示位置" prop="position">
            <!-- <el-input
                v-model="queryParams.position"
                placeholder="请输入素材展示位置"
                clearable
                @keyup.enter="handleQuery"
/> -->
            <InputSelect
              text="请输入位置"
              :modelValue="queryParams.position"
              :options="positionList"
              @update:modelValue="handlePositionSearch"
            />
          </el-form-item>
          <el-form-item label="查找删除数据" prop="delFlag">
            <InputSelect
              text="请选择"
              :modelValue="queryParams.delFlag"
              :options="delFlagList"
              @update:modelValue="handleDeleteSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
        </el-row>
      </template>

      <template #content>
        <el-table :data="bannerList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="编号" align="center" prop="pdId" />

          <el-table-column
            label="专题精选"
            align="center"
            prop="coverImg"
            width="100"
          >
            <template #default="scope">
              <ImagePreview
                :src="scope.row.coverImg"
                :width="80"
                :height="80"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="封面文字"
            align="center"
            prop="coverText"
            width="100"
          >
          </el-table-column>

          <el-table-column
            label="Banner图片"
            align="center"
            prop="url"
            width="100"
          >
            <template #default="scope">
              <ImagePreview :src="scope.row.url" :width="80" :height="80" />
            </template>
          </el-table-column>

          <el-table-column
            label="素材类型"
            align="center"
            prop="materialType"
          />
          <el-table-column label="上传者" align="center" prop="createBy" />
          <el-table-column label="上传时间" align="center" prop="createTime" />
          <el-table-column label="状态" align="center" prop="state">
            <template #default="scope">
              <el-switch
                v-model="scope.row.state"
                inline-prompt
                :inactive-value="1"
                inactive-text="未展示"
                :active-value="0"
                active-text="正常展示"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
        <!-- 添加或修改对话框 -->
        <Dialog
          :show="dialogConfig.show"
          :title="dialogConfig.title"
          :buttons="dialogConfig.buttons"
          width="600px"
          :showCancel="false"
          @close="clear"
          :showClose="false"
          :closeOnClickModal="true"
        >
          <el-form
            ref="classifyRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            label-position="left"
            inline
          >
            <el-form-item label="素材类型" prop="materialType">
              <el-input
                v-model="form.materialType"
                placeholder="请输入素材类型"
                clearable
              /> </el-form-item
            ><el-form-item label="专题精选" prop="coverImg">
              <ImageUpload
                :imageUrl="form.coverImg"
                ref="topicUploadRef"
                @filePath="getTopicPath"
              />
            </el-form-item>
            <!-- <el-form-item label="商品编号" prop="productCode">
                <el-input
                  v-model="form.productCode"
                  placeholder="请输入商品编号"
                />
              </el-form-item> -->
            <el-form-item label="图片" prop="url">
              <ImageUpload
                :imageUrl="form.url"
                ref="uploadRef"
                @filePath="getFilePath"
              />
            </el-form-item>

            <el-form-item label="封面文字" prop="coverText">
              <el-input
                v-model="form.coverText"
                placeholder="请输入封面文字"
                clearable
              />
            </el-form-item>
            <el-form-item label="位置" prop="position">
              <!-- <el-input v-model="form.position" placeholder="请输入图片位置" /> -->
              <InputSelect
                text="请选择展示位置"
                @change="handleSelectChange"
                :modelValue="form.position"
                @update:modelValue="handleSelectChange"
              />
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <template #default>
                <el-switch
                  v-model="form.state"
                  inline-prompt
                  active-text="展示中"
                  :active-value="0"
                  :inactive-value="1"
                  inactive-text="未展示"
                />
              </template>
            </el-form-item>
            <!-- 恢复删除状态 -->
            <el-form-item label="删除标识" prop="delFlag">
              <template #default>
                <el-switch
                  v-model="form.delFlag"
                  inline-prompt
                  active-text="正常使用"
                  :active-value="0"
                  :inactive-value="1"
                  inactive-text="已删除"
                />
              </template>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <!-- 富文本编辑器 -->
              <!-- <editor v-model="form.remark" :min-height="192" /> -->
              <el-input v-model="form.remark" :rows="2" type="textarea" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </Dialog>
      </template>
    </Layout>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  computed,
  onMounted,
  provide,
  toRefs,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import Layout from "@/components/Layout/Layout-common.vue";

import {
  getBannerList,
  getBannerById,
  addBanner,
  updateBanner,
  deleteOssFile,
  deleteData,
} from "@/api/page/home.js";
import Dialog from "@/components/Dialog.vue";
const { proxy } = getCurrentInstance();
// 路径参数
const route = useRoute();
//  路由
const router = useRouter();

const showSearch = ref(true);
// 专题精选图片上传
const topicUploadRef = ref();
const uploadRef = ref();
const single = ref(true);
const multiple = ref(true);
const handleQuery = () => {
  getList();
};

const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    position: "",
  };
  //   getList();
};
// 分页数据
const total = ref(0);
// 表格数据
const bannerList = ref([]);
// 修改、新增弹窗表单数据
const classifyRef = ref();

// 分类数据
const classifyList = ref([
  {
    name: "动漫",
    value: "动漫",
    desc: "",
  },
  { name: "风景", value: "风景", desc: "" },
]);
// 展示位置
const positionList = ref([
  {
    name: "Banner",
    value: "home/banner",
    desc: "首页的Banner部分展示",
  },
  { name: "封面-专题精选", value: "home/cover,classify", desc: "" },
]);
// 删除标志
const delFlagList = ref([
  { name: "正常", value: "0" },
  { name: "删除", value: "1" },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    position: "",
    delFlag: "0",
  },
  rules: {
    materialType: [
      { required: true, message: "请输入素材类型", trigger: "blur" },
      { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
    ],
    // url: [{ required: true, message: "请上传图片", trigger: "blur" }],
    // position: [{ required: true, message: "请输入位置", trigger: "blur" }],
  },
  // 需要删除的文件数组（删除之前存储的文件）
  imgData: [],
});

const dialogConfig = reactive({
  show: false,
  title: "",
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

const { queryParams, form, rules, imgData } = toRefs(data);

onMounted(() => {
  getList();
});
// 获取banner数据
function getList() {
  console.log("queryParams:", queryParams.value);
  getBannerList(queryParams.value).then((response) => {
    bannerList.value = response.rows;
    console.log("bannerList:", bannerList.value);
    total.value = response.total;
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.pid);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  dialogConfig.show = true;
  dialogConfig.title = "添加";
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/productInfo/export",
    {
      ...queryParams.value,
    },
    `productInfo_${new Date().getTime()}.xlsx`
  );
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const pdId = row.pdId || ids.value;
  getBannerById(pdId).then((response) => {
    form.value = response.data;
    //
    dialogConfig.show = true;
    dialogConfig.title = "修改信息";
  });
}

//  删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm("是否确认删除", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    console.log("row:", row);
    // 删除操作
    deleteData(row.pdId)
      .then((result) => {
        if (result.code == 200) {
          ElMessage.success("删除成功");
        }
        if (result.code == 500) {
          ElMessage.error("删除失败");
        }
      })
      .catch((err) => {
        ElMessage.error("删除失败");
      });
  });
  setTimeout(() => {
    getList();
  }, 1000);
};

// 弹框确认  修改/添加
const submitForm = () => {
  // console.log("弹窗标题：", dialogConfig.title);
  // 修改操作
  if (dialogConfig.title == "修改信息") {
    // console.log("修改操作", form.value);
    // 上传新的图片，获取数据
    updateBanner(form.value)
      .then((result) => {
        if (result.code == 200) {
          ElMessage.success("修改成功");
        }
      })
      .catch((err) => {
        ElMessage.error("修改失败");
      });
  }

  // 添加操作
  else if (dialogConfig.title == "添加") {
    // console.log("添加操作", form.value);
    // 校验表单参数，是否填写
    form.value.delFlag = 0;
    addBanner(form.value)
      .then((result) => {
        if (result.code == 200) {
          ElMessage.success("添加成功");
        }
        if (result.code == 500) {
          // ElMessage.error("添加失败");
          // 向后端发起请求，删除刚才上传的文件
        }
      })
      .catch((err) => {});
  }
  // 判断ImgData是否有值，有则
  if (imgData.value.length > 1) {
    console.log("删除方法执行了吗！", imgData.value);
    // 向后端发起请求，删除旧文件
    deleteOssFile(imgData.value);
  }

  // 重新获取数据
  setTimeout(() => {
    getList();
  }, 100);
  dialogConfig.show = false;
};

// 表单重置
function reset() {
  form.value = {
    status: null,
    delFlag: null,
    createUser: null,
    createBy: null,
    createTime: null,
    updateUser: null,
    updateBy: null,
    updateTime: null,
  };
  // classifyRef.value.resetFields();
}

// 数据还原
const clear = () => {
  // 清除上传子组件的文件列表和img
  console.log("clear", uploadRef.value);
  topicUploadRef.value.clearFileList();
  uploadRef.value.clearFileList();
  // 还原表单原始数据
  classifyRef.value.resetFields();
  imgData.value = [];
  dialogConfig.show = false;
};

// 获取文件返回路径
const getFilePath = (filePath) => {
  // 上传文件之前，把前一个文件路径，记录下来
  // 获取文件名
  let fileName = form.value.url?.split("/").pop() || "";
  imgData.value.push(fileName);
  form.value.url = filePath;
  console.log("url:", filePath);
  //   console.log("imgData:", imgData.value);
};

// 获取专题精选的封面图片路径
const getTopicPath = (filePath) => {
  // 上传文件之前，把前一个文件路径，记录下来
  // 获取文件名 保存之前的文件的路径，便于删除
  let fileName = form.value.coverImg?.split("/").pop() || "";
  imgData.value.push(fileName);
  //   修改form的属性值
  form.value.coverImg = filePath;
  console.log("coverImg:", filePath);
};
// 修改/新增页的下拉选择
const handleSelectChange = (val) => {
  // console.log("选择器的值val:", val);
  form.value.position = val;
};

// 搜索-素材分类的下拉菜单
const handleMaterialTypeSearch = (val) => {
  // console.log("搜索的值：", val);
  queryParams.value.materialType = val;
};
// 搜索-展示位置的下拉菜单
const handlePositionSearch = (val) => {
  // console.log("搜索的值：", val);
  queryParams.value.position = val;
};

// 搜索-查找删除数据
const handleDeleteSearch = (val) => {
  queryParams.value.delFlag = val;
};
</script>

<style lang="scss" scoped></style>
